package share;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;

import com.laoxinwen.app.R;

import bean.OAuthInfo;
import bean.wraper.UserInfoWrapper;
import common.HttpCallBack;
import common.Requester;
import common.UserConfig;
import util.FastBlur;
import util.ToastUtil;
import util.bitmap.ImgUtil;

/**
 * Created by ilioili on 2015/3/31.
 */
public class LoginHelper {
    private ShareActivity activit;
    private Bitmap bitmapBg;
    private ViewGroup dialogView;
    private Dialog loginDialog;
    private LoginResultListener loginResultListener;
    public LoginHelper(ShareActivity activit) {
        this.activit = activit;
    }

    public void dismissDialog() {
        clearLoginIcons();
    }

    public void login(LoginType loginType) {
        ShareUserInfo userInfo = UserConfig.getShareUserInfo();
        switch (loginType) {
            case QQ:
                requestLogin(loginType, userInfo.qqOpenId, userInfo.qqName, userInfo.qqIconUrl, userInfo.qqToken);
                break;
            case WECHAT:
                requestLogin(loginType, userInfo.weixinOpenId, userInfo.weixinName, userInfo.wexinIconUrl, userInfo.weixinToken);
                break;
            case SINA:
                requestLogin(loginType, userInfo.sinaOpenId, userInfo.sinaName, userInfo.sinaIconUrl, userInfo.sinaToken);
                break;
        }
    }

    private void requestLogin(final LoginType loginType, String openId, String nickName, String iconUrl, String token) {
        final ShareUserInfo userInfo = UserConfig.getShareUserInfo();
        Requester.login(loginType, openId, nickName, iconUrl, token, new HttpCallBack<UserInfoWrapper>() {
            @Override
            public void onSucceed(UserInfoWrapper data) {
                UserConfig.updateUserInfo(data.getData());
                UserConfig.setIsLogin(true);
                UserConfig.setRequestToken(data.getData().getToken());
                //                switch (UserConfig.getLoginType()) {
                //                    case QQ:
                //                        userInfo.isQqBinded = true;
                //                        break;
                //                    case WECHAT:
                //                        userInfo.isWexinBinded = true;
                //                        break;
                //                    case SINA:
                //                        userInfo.isSinaBinded = true;
                //                        break;
                //                }
                userInfo.isQqBinded = userInfo.isSinaBinded = userInfo.isWexinBinded = false;
                for (OAuthInfo oauth : data.getData().getOauth()) {
                    switch (oauth.getType()) {
                        case OAuthInfo.TYPE_QQ:
                            userInfo.isQqBinded = true;
                            userInfo.qqName = oauth.getExternal_name();
                            break;
                        case OAuthInfo.TYPE_WX:
                            userInfo.isWexinBinded = true;
                            userInfo.weixinName = oauth.getExternal_name();
                            break;
                        case OAuthInfo.TYPE_WB:
                            userInfo.isSinaBinded = true;
                            userInfo.sinaName = oauth.getExternal_name();
                            break;
                    }
                }
                UserConfig.updateShareUserInfo(userInfo);
                UserConfig.setLoginType(loginType);
                if (null != loginResultListener) {
                    loginResultListener.onLoginSucceed();
                }
            }

            @Override
            protected void onNetError() {
                if (null != loginResultListener) {
                    loginResultListener.onLoginSucceed();
                }
                ToastUtil.showShortToast("请检查网络设置");
            }

            @Override
            protected void onServerError(UserInfoWrapper data) {
                if (null != loginResultListener) {
                    loginResultListener.onLoginSucceed();
                }
                ToastUtil.showLongToast(data.getError().getMessage());
            }
        });
    }

    public void setLoginResultListener(LoginResultListener loginResultListener) {
        this.loginResultListener = loginResultListener;
    }

    public void showDialog() {
        showLoginDialog();
    }

    private void showLoginDialog() {
        if (null == loginDialog) {
            loginDialog = new Dialog(activit);
            dialogView = (ViewGroup) activit.getLayoutInflater().inflate(R.layout.login_dialog, null);
            loginDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);//去掉标题
            loginDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                loginDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            }
            loginDialog.setContentView(dialogView);
            loginDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            activit.f(R.id.login_sina, dialogView).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    activit.bindSina();
                }
            });
            activit.f(R.id.login_qq, dialogView).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    activit.bindQq();
                }
            });
            activit.f(R.id.login_wexin, dialogView).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    activit.bindWechat();
                }
            });
            dialogView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clearLoginIcons();
                }
            });
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            View backgroudView = activit.getWindow().getDecorView();
            backgroudView.buildDrawingCache();
            final Bitmap bitmap = Bitmap.createBitmap(backgroudView.getDrawingCache());
            dialogView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    dialogView.getViewTreeObserver().removeOnPreDrawListener(this);
                    bitmapBg = blur(bitmap, dialogView);
                    return true;
                }
            });
        } else {
            dialogView.setBackgroundColor(Color.argb(80, 0, 0, 0));
        }
        loginDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (null != bitmapBg && !bitmapBg.isRecycled()) {
                    bitmapBg.recycle();
                }
            }
        });
        loginDialog.show();
        showLoginIcons();
    }

    public void clearLoginIcons() {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                View vSina = activit.f(R.id.login_sina, dialogView);
                View vQQ = activit.f(R.id.login_qq, dialogView);
                View vWeixin = activit.f(R.id.login_wexin, dialogView);
                TranslateAnimation t1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_PARENT, 1.2f);
                t1.setDuration(500);
                t1.setInterpolator(new AccelerateInterpolator(0.5f));
                vSina.startAnimation(t1);
                TranslateAnimation t2 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_PARENT, 1.2f);
                t2.setDuration(500);
                t2.setInterpolator(new AccelerateInterpolator(0.75f));
                vQQ.startAnimation(t2);
                TranslateAnimation t3 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_PARENT, 1.2f);
                t3.setDuration(500);
                t3.setInterpolator(new AccelerateInterpolator(1f));
                vWeixin.startAnimation(t3);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loginDialog.dismiss();
                    }
                }, 500);
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private Bitmap blur(Bitmap bkg, View view) {
        long startMs = System.currentTimeMillis();
        float scaleFactor = 1;
        float radius = 20;
        scaleFactor = 2;
        radius = 5;
        ImgUtil.checkMemory();
        Bitmap overlay = null;
        try {
            overlay = Bitmap.createBitmap((int) (view.getMeasuredWidth() / scaleFactor), (int) (view.getMeasuredHeight() / scaleFactor), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(overlay);
            canvas.translate(-view.getLeft() / scaleFactor, -view.getTop() / scaleFactor);
            canvas.scale(1 / scaleFactor, 1 / scaleFactor);
            Paint paint = new Paint();
            paint.setFlags(Paint.FILTER_BITMAP_FLAG);
            canvas.drawBitmap(bkg, 0, 0, paint);
            canvas.drawColor(Color.argb(30, 255, 255, 255));

            //        overlay = FastBlur.doBlur(overlay, (int) radius, true);
            overlay = FastBlur.doBlurJniArray(overlay, (int) radius, true);
            view.setBackground(new BitmapDrawable(activit.getResources(), overlay));
        } catch (OutOfMemoryError oom) {
            oom.printStackTrace();
        }
        bkg.recycle();
        return overlay;
    }

    private void showLoginIcons() {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                View vSina = activit.f(R.id.login_sina, dialogView);
                View vQQ = activit.f(R.id.login_qq, dialogView);
                View vWeixin = activit.f(R.id.login_wexin, dialogView);
                TranslateAnimation t1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_PARENT, 1.2f, Animation.RELATIVE_TO_SELF, 0);
                t1.setDuration(500);
                t1.setInterpolator(new DecelerateInterpolator(0.5f));
                vSina.startAnimation(t1);
                TranslateAnimation t2 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_PARENT, 1.2f, Animation.RELATIVE_TO_SELF, 0);
                t2.setDuration(500);
                t2.setInterpolator(new DecelerateInterpolator(0.75f));
                vQQ.startAnimation(t2);
                TranslateAnimation t3 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_PARENT, 1.2f, Animation.RELATIVE_TO_SELF, 0);
                t3.setDuration(500);
                t3.setInterpolator(new DecelerateInterpolator(1f));
                vWeixin.startAnimation(t3);
            }
        });
    }

    public interface LoginResultListener {
        void onLoginFail();

        void onLoginSucceed();
    }
}
